//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================
#include <ddk.h>
#include "timerint.h"

DzEvent g_event;
DzEvent g_eventIST;

ECode ec;


Int32 ThreadFunc(void* arg)
{
    // print interrupt latency
    int nTotalMaxLatency = 0xffff;
    int nTotalTstIndex = 0;
    WaitResult wr;

    while (1) {
        g_event.Wait(&wr, NULL);

        if (nTotalMaxLatency > g_nMaxLatencyBak) {
            nTotalMaxLatency = g_nMaxLatencyBak;
        }

        nTotalTstIndex += TstIndexBak;

        kprintf("\nTSTTIMES   = %d (Total: %d) ",       \
                TstIndexBak, nTotalTstIndex);
        kprintf("\nMaxLatency = %d (Total: %d) ",       \
                g_nMaxLatencyBak, nTotalMaxLatency);
        kprintf("\nTime       = %d ns (Total: %d)\n",   \
                (0xffff - g_nMaxLatencyBak) * 271,      \
                (0xffff - nTotalMaxLatency) * 271);
    }

    return NOERROR;
}

Int32 IST(void* arg)
{
    WaitResult wr;
    while (true) {
        g_eventIST.Wait(&wr, NULL);

        g_nTemp = TIMER3->value;
        if (g_nMaxLatency > g_nTemp) {
            g_nMaxLatency = g_nTemp;
        }

        RestoreIF(g_uFlags);

        // Clears the TIMER3 int
        TIMER3->clear = 0;

        // TIMER3 reload
        TIMER3->load = 0xFFFF;

        TstIndex++;
        if (TstIndex == TSTTIMES) {
            TstIndexBak = TstIndex;
            g_nMaxLatencyBak = g_nMaxLatency;

            TstIndex = 0;
            g_nMaxLatency = 0xffff;

            g_event.Notify(SIGNALED);
        }
    }
    return NOERROR;
}
